<?php

namespace addons\facrm\controller\facrm;

use addons\facrm\library\BackendApi;
use think\Config;
use think\Db;
use think\Exception;
use think\Hook;
use think\Request;

use app\common\exception\UploadException;
use app\common\library\Upload;
use think\Session;


/**
 * 共有无需权限接口
 * @internal
 */
class Common extends BackendApi
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['init','getNoticeTpl'];
    public function _initialize()
    {
        parent::_initialize();
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
    }

    /**
     * 下拉选择
     * @ApiParams(name="model", type="string", required=true, description="默认admin")
     * @ApiParams(name="keyField", type="string", required=true, description="主键字段，如id")
     * @ApiParams(name="type", type="string", required=false, description="可以空all代表获取全部")
     */
    public function selectpage(){

        $modellist=['admin'];
        $model = $this->request->param('model');
        if (!$this->request->request('keyField')){
            $this->error("访问出错");
        }
        if (!in_array($model,$modellist))
            $this->error("非法访问");

        $this->model = model('\app\admin\model\\'.$model);
        $type = $this->request->param('type');


        switch ($model){
            case 'admin':
                $this->selectpageFields =['id','concat(nickname,"(",id,")") as nickname'];
				$custom=['status'=>'normal'];
                if ($type != "all") {
                    $childrenAdminIds = $this->auth->getChildrenAdminIds(true);
					$custom['id']= ['in', $childrenAdminIds];
                }
                //暂时处理授权审批 检索员工出错问题
                if (!$this->request->request('searchField')){
                    $this->request->request(['searchField' => 'nickname']);
                }
                $this->request->request(['custom' => $custom]);
                break;
        }
        return parent::selectpage();

    }

    /**
     * 读取省市区数据,联动列表
     * @ApiMethod (GET)
     * @ApiParams(name="province", type="int", required=true, description="省份ID，可空。空就是获取省份列表不空就是获取城市列表")
     * @ApiParams(name="city", type="int", required=true, description="城市ID，可空，空就是获取城市列表不空就是获取区域列表")
     */
    public function area()
    {
        $params = $this->request->get("row/a");
        if (!empty($params)) {
            $province = isset($params['province']) ? $params['province'] : '';
            $city = isset($params['city']) ? $params['city'] : '';
        } else {
            $province = $this->request->get('province', '');
            $city = $this->request->get('city', '');
        }
        $where = ['pid' => 0, 'level' => 1];
        $provincelist = null;
        if ($province !== '') {
            $where['pid'] = $province;
            $where['level'] = 2;
            if ($city !== '') {
                $where['pid'] = $city;
                $where['level'] = 3;
            }
        }
        $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
        $this->success('',  $provincelist);
    }

    /**
     * 读取所有省市区数据(用于uview select)
     */
    public function getAllArea(){
        $lists= \addons\facrm\model\Area::getAllCacheChildren();
        $this->success('',array_values($lists));
    }

    /**
     * [客户等级、行业类型、来源等]
     */
    public function baseConfig(){
        $this->addon_config = get_addon_config('facrm');
        $this->success('',  [
                'levelList'=>$this->addon_config['level'],
                'industryList'=>$this->addon_config['industry'],
                'sourceList'=>$this->addon_config['source'],
				'accountList'=>$this->addon_config['account'],
                'recordTypeList'=>$this->addon_config['record_type'],
                'cprefix'=>$this->addon_config['cprefix'],//合同编号规则
                'rprefix'=>$this->addon_config['rprefix'],//回款编号规则
                'deal'=>$this->addon_config['deal'],//开启成交(无需走合同流程)
            ]
        );
    }

    /**
     * 基础配置
     * @ApiParams          (name="preview", type="int", required=false, description="只要传递说明是获取装修预览")
     * @ApiReturnParams    (name="login_captcha", type="string", required=false, sample="0",description="是否需要登录验证码")
     * @ApiReturnParams    (name="app_id", type="string", required=false, sample="",description="微信公众号ID")
     * @ApiReturnParams    (name="config.upload", type="array", required=false, sample="",description="上传配置,config.upload.cdnurl是图片地址cdn")
     * @ApiReturnParams    (name="themeconfig", type="obj", required=false, sample="",description="主题配色")
     */
    public function init(){
        $third=get_addon_config('third');
        //配置信息
        $upload = Config::get('upload');

        //如果非服务端中转模式需要修改为中转
        if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
            //临时修改上传模式为服务端中转
            set_addon_config($upload['storage'], ["uploadmode" => "server"], false);
            $upload = \app\common\model\Config::upload();
            // 上传信息配置后
            Hook::listen("upload_config_init", $upload);

            $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
        }

        $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : \request()->domain();
        $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

        $config = [
            'upload' => $upload
        ];
        $themeconfig=array();
        if ($this->request->request('preview')){
            $themeconfig=Session::get("facrmpreviewtheme");//用于预览
        }
        $themeconfig = $themeconfig?$themeconfig:\addons\facrm\library\Theme::get();


        if ($themeconfig){
            $themeconfig=\addons\facrm\library\Theme::render($themeconfig);
        }

        $payConfig=\addons\facrm\library\Order::getPayConfig();

        $this->success('',  [
                'login_captcha'=>Config::get('fastadmin.login_captcha'),//是否需要验证码，
                'app_id'=>isset($third['wechat']['app_id'])?$third['wechat']['app_id']:'',//企业微信公众号
                'config'=>$config,//上传配置
                'themeconfig'=>$themeconfig,//主题设置
                'payConfig'=>($payConfig?$payConfig['values']:[]),//在线收款配置
            ]
        );
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {

        $upload_config=config("upload");
        /**
         * 兼容第三方存储，alioss，其它没有测试。
         */
        if ($upload_config['storage']!='local'){
            
            try {
				Session::set("admin", $this->auth->getAdmin());//兼容需要登录的上传插件
				request()->module('admin');
                $objname="\\addons\\".$upload_config["storage"]."\\controller\\Index";
                $uploadClass=new $objname();
				
				$upload_config=config("upload");
				if (isset($upload_config['multipart'])&&$upload_config['multipart']){
					Request::instance()->post($upload_config['multipart']);
				}
				$uploadClass->upload();
				
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
        }
		
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('上传成功'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('上传成功'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    /**
     * 获取通知模板
     * @ApiParams    (name="type", type="string", required=false, sample="0",description="flow_contract,flow_invoice,clues_customer,flow_receivables,flow_business")
     */
    public function getNoticeTpl(){
        $engine = $this->request->request('engine','Min');
		$type = $this->request->request('type','');//flow_contract ,flow_receivables,clues_customer,flow_business
		
		//由于微信订阅通知最多只能有3条订阅 所以专门做了此修改
		//审批合同相关通知,
		$flow_contract=['notice_flow_contract','notice_pass_contract','notice_nopass_contract'];
		//审批回款通知
		$flow_receivables=['notice_pass_receivables','notice_flow_receivables','notice_nopass_receivables'];
		//线索和客户
		$clues_customer=['notice_flow_customer','notice_expire_ccustomer','notice_flow_clues'];
		//商机
		$flow_business=['notice_flow_business'];
        //发票
        $flow_invoice=['notice_flow_invoice_nopass','notice_invoice_opener'];
		
	
        $data_temp = \addons\facrm\library\notice\Notice::getTempLplData();
        $keys=array();
        foreach ( $data_temp as $row){
			if(isset($$type)&&in_array($row['key'],$$type)){
				 $keys[]=$row['key'].$engine;
			}
        }
        $lists=\app\admin\model\facrm\Setting::where('key','in',$keys)->where('status',1)->select();
        $this->success('',$lists);
    }

    /**
     * 检查权限
     */
    public function authcheck(){
        $auth = $this->request->post('auth');
        $this->success('',($auth&&$this->auth->check($auth))?1:0);
    }

    /**
     * 腾讯地图经纬度返回地址
     * @ApiParams          (name="lat", type="string", required=true, description="lat<纬度>,lng<经度>")
     * @ApiParams          (name="lng", type="string", required=true, description="lat<纬度>,lng<经度>")
     * @ApiReturnParams    (name="address", type="string", required=true, sample="0",description="定位地址")
     */
    public function geocoder(){
        $url="https://apis.map.qq.com/ws/geocoder/v1/";
        $addon_config = get_addon_config('facrm');

        if (!isset($addon_config['map_qq_key'])||!$addon_config['map_qq_key']){
            $this->error('腾讯地图KEY未配置');
        }


        //lat<纬度>,lng<经度>
        $lat=$this->request->get('lat');
        $lng=$this->request->get('lng');
        //location= 39.984154,116.307490
        if (!$lat||!$lng){
            $this->error("经纬度有误");
        }

        $params=['location'=>"{$lat},{$lng}",'key'=>$addon_config['map_qq_key']];

        $cachekey=md5("{$lat},{$lng}");
        $result=cache($cachekey);
        if (!$result){
            //缓存没有才去接口那里获取
            $result=\fast\Http::get($url,$params);
            $result=json_decode($result,true);
            if (!$result||!isset($result['status'])||$result['status']!=0||!isset($result['result']['address'])){
                $this->error('获取地址错误');
            }
            cache($cachekey,$result,86400*30);
        }

        $this->success('',['address'=>$result['result']['address']]);
    }


}
